﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce.Model;
using Ecommerce.Admin.Models;
using Ecommerce.Lib;
using Ecommerce.Lib.Paging;
using Ecommerce.Lib.Common;
using Ecommerce.Admin.Properties;


namespace Ecommerce.Admin.Controllers
{
    public class ArticleCategoryController : Controller
    {
            private ArticleCategoryViewModel c = new ArticleCategoryViewModel();
            private ArticleCategoryDataModel cd = new ArticleCategoryDataModel();
            private TMDTDataContext db = new TMDTDataContext();
            //[Authorize]
            public ActionResult Index()
            {
                var categories = db.ArticleCategories.OrderByDescending(a =>a.Priority).ToList();
                c.TreeCategories = cd.MenuTreeNode(0, categories).Reverse().ToList();
                c.Categories = cd.MenuTree(0, categories, 0);
                c.ImagePath = Settings.Default.SiteRootUrl + Settings.Default.CategoryArticleUrl;
                return View(c);
            }
            static bool submit = false;
            //[Authorize]
            public ActionResult Create()
            {
                var categories = db.ArticleCategories.ToList();
                c.Categories = cd.MenuTree(0, categories, 0);
                ViewData["Notice"] = submit == false ? "display:none" : "display:block";
                submit = false;
                return View(c);
            }
            //[Authorize]
            [ValidateInput(false)]
            [ValidateAntiForgeryToken]
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                ArticleCategory cat = new ArticleCategory();
                cat.Title = Request.Form["Title"];
                cat.ParentID = !string.IsNullOrEmpty(Request.Form["ParentID"]) ? int.Parse(Request.Form["ParentID"]) : 0;
                //cat.Priority = Utils.ParseInt(Request.Form["Priority"]);
                cat.Priority = cat.ID;
                cat.Description = Request.Form["Description"];
                HttpPostedFileBase img = Request.Files["ImagePath"];
                if (!string.IsNullOrEmpty(img.FileName))
                {
                    UploadFile.UploadFileToDirectory(img, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.CategoryArticleRootPath));
                    cat.ImagePath = img.FileName;
                }
                else
                {
                    cat.ImagePath = "default.jpg";
                }
                cat.Status = bool.Parse(Request.Form["Status"]);
                db.ArticleCategories.InsertOnSubmit(cat);
                db.SubmitChanges();
                if (Request.Form["CheckType"].Equals("save_and_back"))
                {
                    return RedirectToAction("Index");
                }
                else if (Request.Form["CheckType"].Equals("save_and_check"))
                {
                    submit = true;
                    return RedirectToAction("Create");
                }
                return RedirectToAction("Index");
            }
           // [Authorize]
            public ActionResult Edit(int? id)
            {
                if (!id.HasValue) return RedirectToAction("Index");
                c.Category = db.ArticleCategories.SingleOrDefault(d => d.ID == id);
                var categories = db.ArticleCategories.ToList();
                c.Categories = cd.MenuTree(0, categories, c.Category.ParentID);
                ViewData["ImagePath"] = string.Format("{0}{1}", Settings.Default.SiteRootUrl, Settings.Default.CategoryArticleUrl);
                ViewData["Notice"] = submit == false ? "display:none" : "display:block";
                c.ImagePath = Settings.Default.SiteRootUrl + Settings.Default.ArticleRootUrl;
                submit = false;
                return View(c);
            }
           // [Authorize]
            [ValidateInput(false)]
            [ValidateAntiForgeryToken]
            [HttpPost]
            public ActionResult Edit(FormCollection collection, int? id)
            {
                var cat = db.ArticleCategories.SingleOrDefault(d => d.ID == id);
                cat.Title = Request.Form["CategoryName"];
                cat.ParentID = !string.IsNullOrEmpty(Request.Form["CategoryId"]) ? int.Parse(Request.Form["CategoryId"]) : 0;
                cat.Priority = Ecommerce.Lib.Common.Utils.ParseInt(Request.Form["Priority"]);
                HttpPostedFileBase img = Request.Files["ImagePath"];
                if (!string.IsNullOrEmpty(img.FileName))
                {
                    if (!string.IsNullOrEmpty(cat.ImagePath))
                    {
                        var mapPath = string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.CategoryArticleRootPath);
                        System.IO.File.Delete(mapPath + cat.ImagePath);
                    }

                    UploadFile.UploadFileToDirectory(img, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.CategoryArticleRootPath));
                    cat.ImagePath = img.FileName;
                }           
                db.SubmitChanges();

                if (Request.Form["CheckType"].Equals("save_and_back"))
                {
                    return RedirectToAction("Index");
                }
                else if (Request.Form["CheckType"].Equals("save_and_check"))
                {
                    submit = true;
                    return RedirectToAction("Edit");
                }
                return RedirectToAction("Index");
            }
           // [Authorize]
            public ActionResult ChangeStatus(string id)
            {
                var p = db.ArticleCategories.SingleOrDefault(d => d.ID.Equals(id));
                p.Status = p.Status == true ? p.Status = false : p.Status = true;
                db.SubmitChanges();
                string img = p.Status == true ? "<img src='/Content/Images/icon_active.png' style='cursor:pointer' title='Hiển thị' class='changeStatus' id='" + id + "' />" : "<img style='cursor:pointer' title='Không hiển thị' src='/Content/Images/icon_inactive.png' class='changeStatus' id='" + id + "' />";
                return Content(img);
            }
           // [Authorize]
            public ActionResult Delete(int? id)
            {
                if (!id.HasValue) return RedirectToAction("Index");
                var checkParent = cd.NodeToDelete(id.Value, db.ArticleCategories.ToList());
                if (checkParent.Count > 0)
                {
                    foreach (var item in checkParent)
                    {
                        var pr = db.Articles.Where(d => d.CategoryID == int.Parse(item)).ToList();
                        foreach (var k in pr)
                        {
                            //k.CategoryID = null;
                            db.Articles.DeleteOnSubmit(k);
                            db.SubmitChanges();
                        }
                        db.ArticleCategories.DeleteOnSubmit(db.ArticleCategories.SingleOrDefault(d => d.ID.Equals(item)));
                        db.SubmitChanges();
                    }
                }
                var prRoot = db.Articles.Where(d => d.CategoryID == id).ToList();
                foreach (var k in prRoot)
                {
                    //k.CategoryID = null;
                    db.Articles.DeleteOnSubmit(k);
                    db.SubmitChanges();
                }
                db.ArticleCategories.DeleteOnSubmit(db.ArticleCategories.SingleOrDefault(d => d.ID == id));
                db.SubmitChanges();
                return RedirectToAction("Index");
            }
            public ActionResult UpdateAjax(int id, string Value, string pType)
            {
                var p = db.ArticleCategories.SingleOrDefault(d => d.ID == id);
                if (pType.ToLower().Equals("sortid"))
                {
                    p.Priority = int.Parse(Value);
                }
                db.SubmitChanges();
                return null;
            }
        }
    }

